//
//  ZYColorCheckButton.m
//  YiLin
//
//  Created by Zyark on 2018/6/11.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYColorCheckButton.h"

@implementation ZYColorCheckButton
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTaped:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}

-(void)setTitle:(NSString *)title
{
    _title = title;
    [self setNeedsDisplay];
}

-(void)setCheckImage:(UIImage *)checkImage
{
    _checkImage = checkImage;
}

-(void)setCheckBackColor:(UIColor *)checkBackColor
{
    _checkBackColor = checkBackColor;
    [self setNeedsDisplay];
}

-(void)setTextColor:(UIColor *)textColor
{
    _textColor = textColor;
    [self setNeedsDisplay];
}

-(void)setChecked:(BOOL)checked
{
    _checked = checked;
    [self setNeedsDisplay];
}

-(void)onTaped:(UITapGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer locationInView:self];
    if (CGRectContainsPoint(checkRect, point)) {
        NSLog(@"check");
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
    if (CGRectContainsPoint(self.bounds, point)) {
        NSLog(@"text");
        [self sendActionsForControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)drawRect:(CGRect)rect
{
    CGSize txtsize = [self.title sizeWithFont:self.font];
    checkRect = CGRectMake((self.bounds.size.width - txtsize.width - 12 - 2) / 2, (self.bounds.size.height - 12) / 2 - 0.5, 12, 12);
    
    CGMutablePathRef path = CGPathCreateMutable();
    //将矩形添加到路径中
    CGPathAddRect(path, NULL, checkRect);
    //获取上下文
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    //将路径添加到上下文
    CGContextAddPath(currentContext, path);
    //设置矩形填充色
    [self.checkBackColor setFill];
    //矩形边框颜色
    //[[UIColor brownColor] setStroke];
    //边框宽度
    //CGContextSetLineWidth(currentContext,5.0f);
    //绘制
    CGContextDrawPath(currentContext, kCGPathFill);
    CGPathRelease(path);
    
    if (self.checked) {
        if (self.checkImage) {
            [self.checkImage drawInRect:checkRect];
        }
    }
    
    //绘制文字
    titleRect = CGRectMake((self.bounds.size.width - txtsize.width - 12 - 3)/2 + 12 + 2, (self.bounds.size.height - txtsize.height)/2, txtsize.width, txtsize.height);
    
    CGContextSetLineWidth(currentContext, 1.0);
    //CGContextSetRGBFillColor (currentContext, 0.5, 0.5, 0.5, 0.5);
    //UIFont *font = [UIFont boldSystemFontOfSize:18.0];
    [self.textColor setFill];
    NSDictionary *attribute=@{NSFontAttributeName:self.font};
    [self.title drawWithRect:titleRect options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
//    [self.title drawInRect:titleRect withFont:self.font];
    
}
@end
